package com.bowen.demo.demo003.service;

import com.alibaba.fastjson.JSON;
import com.bowen.demo.demo003.request.CbsFrontEndLogRequest;
import com.bowen.demo.demo003.request.FrontEndLogName;
import com.bowen.demo.demo003.result.CbsFrontEndLogResult;
import com.bowen.demo.demo003.result.CbsResult;
import com.bowen.demo.demo003.utils.DateUtils;
import com.bowen.demo.demo003.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 日志查询Service
 * 公众号【猿码天地】
 */
@Slf4j
@Service
public class CbsFrontEndMonitorService{

	// 服务器日志目录
	@Value("${cbs.frontEnd.logPath:D:/project-prod/monitor/logs/}")
	private String cbsFrontEndLogPath;

	// 服务器请求URL
	@Value("${cbs.frontEnd.server.address:http://127.0.0.1:8081/monitor/frontend/log}")
	private String cbsFrontEndServerAddress;

    /**
     * 查询日志
     * @param request
     * @return
     */
    public CbsResult<List<CbsFrontEndLogResult>> showFrontEndLog(CbsFrontEndLogRequest request) {
        if(request == null) {
            log.error("CBS前置机日志-请求参数request为空");
        }
        String logFile = null;
		List<String> result = new ArrayList<>();
		List<CbsFrontEndLogResult> cbsFrontEndLogResults = new ArrayList<>();
		FrontEndLogName frontEndLogName = FrontEndLogName.getByCode(request.getFileLogType());
		try {
			if (null != frontEndLogName) {
				logFile = frontEndLogName.getName() + "_" + DateUtils.format(new Date(), "yyyyMMdd") + ".log";
			}
			Map<String, String> param = new HashMap<>();
			param.put("logFile", cbsFrontEndLogPath + logFile);
			param.put("line", String.valueOf(request.getLine()));
			String cbsFrontEndLogs = HttpClientUtils.doPostJson(cbsFrontEndServerAddress, JSON.toJSONString(param));
			log.debug("CBS前置机日志读取返回：{}",cbsFrontEndLogs);
			if (StringUtils.isNotBlank(cbsFrontEndLogs)) {
				result = JSON.parseObject(cbsFrontEndLogs, List.class);
			}
		}catch (Exception e){
			log.error("CBS前置机日志读取异常， request：{}", JSON.toJSONString(request), e);
		}
		CbsFrontEndLogResult cbsFrontEndLogResult = null;
		for (String log :result) {
			cbsFrontEndLogResult = new CbsFrontEndLogResult();
			//委托付款:脱敏数据,暂时粗范围处理含key=value格式数据
			if(frontEndLogName.getCode().equals(FrontEndLogName.PaymentService.getCode())) {
				final String[] newlog = {log};
				Arrays.stream(log.split(";")).forEach(kv -> {
					System.out.println(kv);
					int pos = kv.indexOf("=");
					if (pos > 0) {
						String val = kv.substring(pos + 1, kv.length());
						newlog[0] = newlog[0].replace(val, "***");
					}
				});
				log = newlog[0];
			}
			cbsFrontEndLogResult.setLog(log);
			cbsFrontEndLogResults.add(cbsFrontEndLogResult);
		}
		return new CbsResult<List<CbsFrontEndLogResult>>(cbsFrontEndLogResults);
    }

}